package com.mc.java8;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.Optional;

/**
 * java8 optional learn
 */
@Slf4j
public class OptionalTest {

    public static void main(String[] args) throws Exception {

        Optional<Student> studentOptional = Optional.empty();

        Student student1 = null;
        //会抛异常   Objects.requireNonNull(value)
       /* Optional<Student> student11 = Optional.of(student1);
        Student student2 = student11.get();*/
        //不会抛异常，默认返回一个空的对象
        Optional<Student> studentOptional1 = Optional.ofNullable(student1);

        //orElse
        Student student = Optional.ofNullable(student1).orElse(createStudent());
        log.info("student:{}", JSON.toJSONString(student));
        //orElseGet  如果值不为null的时候不会执行createStudent
        Student student2 = Optional.ofNullable(student1).orElseGet(() -> createStudent());
        log.info("student2:{}", JSON.toJSONString(student2));

        try {
            Optional.ofNullable(student).orElseThrow(() -> new Exception("出现异常"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("student2:{}", JSON.toJSONString(student2));

        student = null;

        /*  String s = Optional.ofNullable(student).map(x -> x.getAddress().getCity()).get();*/
        Optional.ofNullable(student).map(x -> x.getAddress()).map(a -> a.getCity()).orElseThrow(() -> new Exception("未知异常"));
    }

    public static Student createStudent() {
        Student student = new Student();
        student.setName("zhangsna");
        Address address = new Address();
        address.setCity("xian");
        student.setAddress(address);
        log.info("返回创建对象");
        return student;
    }

    public String getCity(Student st) throws Exception {
        if (Objects.isNull(st)) {
            throw new Exception("业务异常");
        }
        if (st.getAddress() == null) {
            throw new Exception("业务异常");
        }
        String city = st.getAddress().getCity();
        return city;
    }

    public String getCityByOptional(Student st) throws Exception {

        Optional.ofNullable(st).map(x -> x.getAddress()).map(y -> y.getCity()).orElseThrow(() -> new Exception("optional 未知异常"));
        return Optional.ofNullable(st).map(x -> x.getAddress()).map(y -> y.getCity()).orElse("");

    }


}
